package com.shang.springboot1.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileController {
    @PostMapping("/upload")
    public String upload(String name, MultipartFile f, HttpServletRequest request) throws IOException {
        //文件路径
        String path=request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        saveFile(f,path);
        return "上传成功";
    }

    private void saveFile(MultipartFile f,String path) throws IOException{
        //判断存储的路径是否存在，不存在则创建
        File upDir=new File(path);
        if(!upDir.exists()){
            upDir.mkdir();
        }
        //文件存储的路径
        File file=new File(path+f.getOriginalFilename());
        f.transferTo(file);
    }
}
